import React, { useEffect, useState } from 'react'
import { Modal, message } from 'antd'
import CollectionCreateForm from './CollectionCreateForm'
import axios from 'axios'
import { addAlgor, getAlgor } from '@/apis/algor'

const CollectionCreateFormModal = ({ open, onCreate, onCancel, getAlgorList }) => {
  const [formInstance, setFormInstance] = useState()
  const [fileList, setFileList] = useState([])

  const handleCreate = async () => {
    try {
      const values = await formInstance?.validateFields()
      console.log(values)

      const formData = new FormData()
      fileList.forEach(file => {
        formData.append('files', file.originFileObj)
      })
      formData.append('name', values.name)
      formData.append('url', values.url)
      formData.append('tag', values.tag)
      formData.append('title', values.title)
      formData.append('description', values.description)
      formData.append('index', values.index)
      addAlgor(formData)
      onCreate()
      onCancel()
    } catch (error) {
      message.error('请检查并完成所有必填项')
    }

  }

  useEffect(()=>{
    getAlgor()
  },[])

  return (
    <Modal
      open={open}
      title="上传算法"
      okText="添加"
      cancelText="取消"
      okButtonProps={{
        autoFocus: true,
      }}
      onCancel={onCancel}
      destroyOnClose
      onOk={handleCreate}
    >
      <CollectionCreateForm
        onFormInstanceReady={(instance) => {
          setFormInstance(instance)
        }}
        onFileListChange={setFileList}
      />
    </Modal>
  )
}

export default CollectionCreateFormModal